export class Utils {
    constructor() {
        this.throttleBackTime = 0;
        this.throttleGapTime = 0;
        this.throttleEnterTime = 0;
        this.debounceTimer;
        this.debounceGapTime = 0;
    }

    /**
     * 节流函数
     * @param {Function} fn 要执行的方法
     * @param {Number} interval 等待时间，默认500ms
     */
    throttle(fn, interval) {
        this.throttleGapTime = interval || 500;
        (() => {
            this.throttleBackTime = new Date();
            if (this.throttleBackTime - this.throttleEnterTime > this.throttleGapTime) {
                fn.call(this, arguments);
                this.throttleEnterTime = this.throttleBackTime;
            }
        })();
    }

    // 重置节流函数（仅供特殊情况使用）
    resetThrottle() {
        this.throttleBackTime = 0;
        this.throttleGapTime = 0;
        this.throttleEnterTime = 0;
    }

    /**
     * 防抖函数
     * @param {Function} fn 要执行的方法
     * @param {Number} interval 等待时间，默认500ms
     */
    debounce(fn, interval) {
        this.debounceGapTime = interval || 500;
        (() => {
            clearTimeout(this.debounceTimer);
            this.debounceTimer = setTimeout(() => {
                fn.call(this, arguments);
            }, this.debounceGapTime);
        })();
    }

    // 获取导航栏高度
    getNavigationHeight() {
        let windowWidth;
        wx.getSystemInfo({
            success: res => windowWidth = res.windowWidth,
        });
        let {height, top, right} = wx.getMenuButtonBoundingClientRect(); //获取胶囊按钮尺寸信息
        return height + top + windowWidth - right;
    }

    // 获取当前页面URL及参数
    getCurrentPage() {
        let routes = getCurrentPages(); //获取当前打开过的页面路由数组
        let curRoute = routes[routes.length - 1].route; //获取当前页面路由
        let curParam = routes[routes.length - 1].options; //获取路由参数
        // 拼接参数
        let param = '';
        for (let key in curParam) {
            param += '&' + key + '=' + curParam[key];
        }
        return {
            curUrl: curRoute,
            curParam: curParam
        };
    }

    /**
     * 时间格式化
     * @param timestamp 时间戳
     * @return {string} 格式化后的时间
     */
    timestampToTime(timestamp) {
        let date = new Date(timestamp);
        let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '月';
        let D = date.getDate() + '日 ';
        let h = date.getHours() + ':';
        let m = date.getMinutes() + '';
        return M + D + h + m;
    }
}

